<?php

/**
 * 后台管理员model操作
 * @author  xiaobai
 * @date    2017-02-12
 */

namespace app\common\model;

use think\Model;
use think\helper\Hash;
use util\Verify;

class Admin extends Model
{

    protected $pk     = 'id';
    protected $autoWriteTimestamp = 'datetime'; // 自动写入时间，格式为Y-m-d H:i:s
    protected $auto = ['password'];

    // status 的获取器
    public function getStatusTextAttr($value, $data)
    {
        $status = [0=>'禁用',1=>'正常'];
        return $status[$data['status']];
    }

    // group_id 的获取器
    public function getGroupIdAttr($value,$data)
    {
        $group_id = explode(',', $data['group_id']);
        return $group_id;
    }

    // password 修改器 密码加密
    protected function setPasswordAttr($value, $data)
    {
        if ($value == '' || is_null($value)) {
            return $data;
        }
        $pwd =  Hash::make((string)$value);
        return $pwd;
    }

    // 把所属用户组转换成字符串
    public function setGroupIdAttr($value, $data)
    {
        if ($value == '' || is_null($value)) {
            return $data;
        }

        $group_id = implode(',', $value);
        return $group_id;
    }

    // 查询单条记录
    public function find($where)
    {
        $this->where($where)->find()->toArray();
    }

    /**
     * 验证登录信息
     * @param string $account   登录账号、手机号、邮箱
     * @param string $password  登录密码
     * @return bool
     */
    public function login($account = '', $password = '')
    {
        $Verify = new Verify();
        // 匹配登录方式
        if ($Verify->isEmail($account)) {
            $map['email'] = $account;
        } elseif ($Verify->isMobile($account)) {
            $map['mobile'] = $account;
        } else {
            $map['account'] = $account;
        }

        $map['status'] = 1;

        // 查找用户
        $user = $this::get($map);
        if (!$user) {
            $this->error = '用户不存在或被禁用！';
            return false;
        }
        // 检查是否分配用户组
        if ($user['group_id'] == '' || $user['group_id'] == '0') {
            $this->error = '禁止访问，原因：未分配角色！';
            return false;
        }
        if (!Hash::check((string)$password, $user->password)) {
            $this->error = '密码错误！';
            return false;
        }

        $this->startTrans();
        $time = date('Y-m-d H:i:s');
        $ip   = get_client_ip();
        $user = tp_object_array($user);

        $user_where = array('id'=>$user['id']);
        $user_data  = array(
            'last_login_time' => $time,
            'last_login_ip'   => $ip,
        );
        if ($this->where($user_where)->update($user_data) === false) {
            $this->rollback();
            $this->error = '登录失败，请重新登录';
            return false;
        }

        $log_data = array(
            'admin_id'   => $user['id'],
            'nicename'   => $user['nicename'],
            'login_ip'   => $ip,
            'login_time' => $time,
        );
        $admin_log = model('AdminLog');
        if (!$admin_log->save($log_data)) {
            $this->rollback();
            $this->error = '登录失败，请重新登录';
            return false;
        }

        $group_where  = array(array('groupid', 'in', $user['group_id']));
        $group_menuid = model('GroupMenu')->where($group_where)->fetchSql(1)->column('menuid');

        session('admin_id', $user['id']);
        session('nicename', $user['nicename']);
        session('group_id', $user['group_id']);
        session('group_menuid', $group_menuid);
        session('expires_time', time()+3600*2);

        $this->commit();
        return $user['id'];
    }
}
